let users = [
    {
        "address": "天津市-天津市-和平区-2341qwe123",
        "birthday": 1652889600000,
        "email": "862995359@qq.com",
        "gender": 1,
        "id": 1,
        "img": "https://uni1024.oss-cn-hangzhou.aliyuncs.com/mall-system/images/users/woaini/2022-05-221653211267494.jpeg",
        "password": "123456",
        "role": {
            "id": 4,
            "name": "管理员"
        },
        "tel": "13311111111",
        "usercode": "woaini",
        "username": "woaini"
    }
]
let page = {
        "current": 1,
        "optimizeCountSql": true,
        "orders": [],
        "pages": 1,
        "records": [
            {
                "address": "天津市-天津市-和平区-2341qwe123",
                "birthday": 1652889600000,
                "email": "862995359@qq.com",
                "gender": 1,
                "id": 1,
                "img": "https://uni1024.oss-cn-hangzhou.aliyuncs.com/mall-system/images/users/woaini/2022-05-221653211267494.jpeg",
                "password": "123456",
                "role": {
                    "id": 4,
                    "name": "管理员"
                },
                "tel": "13311111111",
                "usercode": "woaini",
                "username": "woaini"
            },
        ],
        "searchCount": true,
        "size": 5,
        "total": 1
}
let roleType = [
        {
            "id":1,
            "name":"游客"
        },
        {
            "id":2,
            "name":"普通用户"
        },
]
let $entry_userroles = $('#admin-card-user-list-entry')
let $entry_pages=$('#admin-card-user-pages-entry')
let $entry_role_dropdown=$('#admin-user-role-dropdown-entry')
let $preload = $('#admin-user-center-placeholder')
function renderUserRoles(users, delay, callback){
    console.log(users)
    $entry_userroles.html('')
    setTimeout(function (){
       callback()
        users.forEach(function (user, index){

            let fn_modify = "renderModal('" + user['id'] + "', '" + user['role']['id'] + "')"
            $entry_userroles.append(`
            <tr valign="baseline">
                <td><input type="checkbox" class="cb_role" data-rid="${user['role']['id']}" data-code="${user['usercode']}" style="width: 20px; height: 20px;"></td>
                <td>${user['id']}</td>
                <td>${user['usercode']}</td>
                <td>${user['username']}</td>
                <td><img src="${user['img']}" width="80px" height="80px" style="border-radius: 50%;"/></td>
                <td>${user['role']['name']}</td>
                <td>
                     <button class="btn btn-primary w-75" data-bs-toggle="modal" data-bs-target="#modal-role" onclick="${fn_modify}">编辑</button>
                </td>
          </tr>
        `)
        })
    }, delay)
}
///// 跳转到指定页
function toPage(inputId, mini, maxi){
    $input = $('#' + inputId)
    let page = $input.val()
    // 限制页面的范围
    page = Math.min(page, maxi)
    page = Math.max(page, mini)
    location.href = paramUpdateCurrentParam('pageNum', page)
}

// 加载分页
function renderRolePage(page){
    $entry_pages.html('')
    let $perPage = $(`<li></li>`)
    // 渲染尾部
    let $tail = `<li class="align-self-center">
                &nbsp;&nbsp;到第&nbsp;&nbsp;
            </li>
            <li class="align-self-center">
                <input id="admin-user-input-to-page" class="input-group" name="pageNum" size="5">
            </li>
            <li class="align-self-center">
                &nbsp;页&nbsp;
            </li>
            <li class="align-self-center">
                <button class="btn btn-outline-dark" onclick="toPage('admin-user-input-to-page', 1, page.pages)">确定</button>
            </li>`
    // 渲染每一页
    for (let i = page.startPage; i <= page.endPage; i++) {
        if(i === page.current){ // 渲染当前页，设置一个高亮的效果
            $perPage.append(`
            <li class="page-item mx-2 active" aria-current="page">
             <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', i)}">${i}</a>
         </li>`)
        } else {
            $perPage.append(`
             <li class="page-item mx-2" aria-current="page">
                 <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', i)}">${i}</a>
             </li>`
            )
        }
    }
    $entry_pages.html('')
    $entry_pages.html(`
            <ul class="pagination mx-auto justify-content-center">
            <li class="align-self-center me-3 rounded-3">
                    第 ${page.current} 页 &nbsp;&nbsp; 共 ${page.pages} 页
            </li>
            <li class="page-item ms-page">
                 <a class="page-link" href="${paramUpdateCurrentParam('pageNum', 1)}">
                    首页
                 </a>
            </li>
            <!--上一页-->
           <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.prePage)}">上一页</a>
            </li>`
        + $perPage.html() + `
            <!--下一页-->
             <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.nextPage)}">下一页</a>
            </li>
            <!--最后一页-->
             <li class="page-item ms-page" href="/index.html?pageNum=${page.pages}">
                  <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.pages)}">末页</a>
             </li>` + $tail +
        `</ul>`)
    $('#textShowResult').text('共 ' + page.total + ' 条结果')

}
// 获取 users
// 渲染角色的下拉菜单
function renderRoleDropdown(roleType){
    $entry_role_dropdown.html('')
    roleType.forEach(function (role){
        $entry_role_dropdown.append(`
              <li><a class="dropdown-item" href="${paramUpdateCurrentParams(['typeId', 'pageNum'], [role.id, 1])}">${role.name}</a></li>
        `)
    })
    $entry_role_dropdown.prepend(`<li><a class="dropdown-item" href="${paramDeleteCurrentURLNot('typeId')}"</a>全部角色</li>`)
}
// 编辑某个用户的角色时渲染修改的模态框
function renderModal(user_id, role_id){
    $('#modal-userCode').val(user_id)
    let $select = $('#modal-select')
    $select.html(``)
    let roles = ajaxGetAllRoleType()
    roles.forEach(function (role){
        $select.append(`<option value='${role.id}'>${role.name}</option>`)
    })
    $select.val(role_id)
}
// 编辑选中用户的角色时，渲染修改的模态框， 数据从选择框所选中的标签里获取
function renderModalBySelected(){
    userCodes  = []
    role = []
    $('.cb_role').each(function (index, obj){
        if($(this).prop('checked') === true){
            // 根据HTML元素的相对关系，定位到用户账号
            userCodes.push($(this).parent().next().text())
            // 同上，定位到当前用户的角色
            role.push($(this).data('rid'))
        }
    })
    if(role.length == 0 || userCodes.length != role.length){
        ms_show_toast(false, '请选择需要处理的角色')
    }
    // 将用户账号以逗号连接起来，角色则默认选择第一个用户的角色
    let code = ''
    for(let i = 0; i < userCodes.length; i++){
        if(i == 0)
            code = userCodes[i]
        else
            code = code + ',' + userCodes[i]
    }
    renderModal(code, role[0])
}

function ajaxGetAllUserWithRole(){
     let data = ajaxPostJsonByCurrentUrlParam('/role/select')
    // 计算上一页和下一页
    let prePage = Math.max(1, data['current'] - 1)
    let nextPage = Math.min(data['current'] + 1, data['pages'])
    let startPage = Math.max(prePage - 1, 1)
    let endPage = Math.min(nextPage + 1, data['pages'])
    data['prePage'] = prePage
    data['nextPage'] = nextPage
    data['startPage'] = startPage
    data['endPage'] = endPage
    return data
}
// 停止加载
function ajaxGetAllRoleType() {return ajaxPostJSON('/role/selectall')}

function stopLoadUI(){
    $preload.html('')
}
// 开启加载
function startLoadUI(){
    $preload.html(`
     <div class="spinner-border text-center" role="status">
        <span class="visually-hidden">Loading...</span>
    </div>
    `)
}
$('#btn-search-role').click(function (){
    $input = $(this).siblings('input')
    if($input.val().length > 0)
        location.href = paramUpdateCurrentParam('username', $input.val())
    else
        location.href = paramDeleteCurrentURLNot('username')
})


// 按键监听
$(document).keydown(function(event){
    if (event.keyCode === 13) {//回车键登陆
        $('#btn-search-role').click()
    }
});

// 修改用户的角色
$('#modal-sure').click(function (){
    let btn_id = $(this).attr('id')
    ms_btn_disable(btn_id, '保存中')
    setTimeout(function (){
        $.ajax({
            url: '/role/update/' + $('#modal-userCode').val(),
            data: {'roleId':$('#modal-select').val()},
            type: 'POST',
            dataType: 'json',
            error: (err) =>{
                ms_show_toast(false, err.responseText)
                console.error(err.responseText)
                ms_btn_enable(btn_id, '保存')
            },
            success: (result)=> {
                if(result['code'] === CODE_SUCCESS){
                    ms_show_toast_callback(true, result['msg'], function (){
                        location.reload()
                    })
                }
                ms_btn_enable(btn_id, '保存')
            }
        })
    }, DELAY_TOAST_WHEN_BTN)
})
////////////////// 全选
$('#cb_all').change(function (){
    $('.cb_role').prop('checked', $(this).prop('checked'))
})


$(document).ready(function (){
    page = ajaxGetAllUserWithRole()
    roleType = ajaxGetAllRoleType()
    startLoadUI()
    renderRoleDropdown(roleType)
    renderUserRoles(page['records'], DELAY_LOAD_USER_BASE, () => stopLoadUI())
    renderRolePage(page)
})